package com.xy.webadmin.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;

import com.xy.common.core.annotation.MyDataSourceResolver;
import com.xy.common.core.base.dao.BaseDaoMapper;
import com.xy.common.core.base.service.BaseService;
import com.xy.common.core.exception.MyRuntimeException;
import com.xy.common.core.object.MyRelationParam;
import com.xy.common.core.object.TokenData;
import com.xy.common.core.util.MyModelUtil;
import com.xy.common.sequence.wrapper.IdGeneratorWrapper;
import com.xy.webadmin.upms.dao.MobileMenuDataPermMapper;
import com.xy.webadmin.upms.dao.MobileMenuMapper;
import com.xy.webadmin.upms.dao.MobileMenuRoleMapper;
import com.xy.webadmin.upms.model.MobileMenu;
import com.xy.webadmin.upms.model.MobileMenuDataPerm;
import com.xy.webadmin.upms.model.MobileMenuRole;
import com.xy.webadmin.upms.service.MobileMenuService;
import com.xy.webadmin.upms.util.MobileMenuDataSourceResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@MyDataSourceResolver(resolver = MobileMenuDataSourceResolver.class)
@Service("mobileMenuService")
public class MobileMenuServiceImpl extends BaseService<MobileMenu, Long> implements MobileMenuService {

    @Autowired
    private MobileMenuMapper mobileMenuMapper;
    @Autowired
    private MobileMenuRoleMapper mobileMenuRoleMapper;
    @Autowired
    private MobileMenuDataPermMapper mobileMenuDataPermMapper;
    @Autowired
    private IdGeneratorWrapper idGenerator;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<MobileMenu> mapper() {
        return mobileMenuMapper;
    }

    @Override
    public List<MobileMenu> getAllListByOrder(String... orderByProperties) {
        TokenData tokenData = TokenData.takeFromRequest();
        if (tokenData.getTenantId() == null) {
            return super.getAllListByOrder(orderByProperties);
        }
        MobileMenu filter = new MobileMenu();
        filter.setTenantId(tokenData.getTenantId());
        filter.setTenantAvailable(true);
        List<String> columns = new ArrayList<>(orderByProperties.length);
        for (String orderByProperty : orderByProperties) {
            columns.add(this.safeMapToColumnName(orderByProperty));
        }
        QueryWrapper<MobileMenu> qw = new QueryWrapper<>(filter);
        return mapper().selectList(qw.orderByAsc(columns));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MobileMenu saveNew(MobileMenu mobileMenu, String roleIdListString) {
        mobileMenuMapper.insert(this.buildDefaultValue(mobileMenu));
        this.insertRelatedData(mobileMenu.getMenuId(), roleIdListString);
        return mobileMenu;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(
            MobileMenu mobileMenu,
            MobileMenu originalMobileMenu,
            String roleIdListString) {
        mobileMenuRoleMapper.delete(
                new LambdaQueryWrapper<MobileMenuRole>().eq(MobileMenuRole::getMenuId, mobileMenu.getMenuId()));
        this.insertRelatedData(mobileMenu.getMenuId(), roleIdListString);
        mobileMenu.setTenantId(originalMobileMenu.getTenantId());
        mobileMenu.setCreateUserId(originalMobileMenu.getCreateUserId());
        mobileMenu.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        mobileMenu.setCreateTime(originalMobileMenu.getCreateTime());
        mobileMenu.setUpdateTime(new Date());
        mobileMenu.setMenuType(originalMobileMenu.getMenuType());
        mobileMenu.setTenantAvailable(originalMobileMenu.getTenantAvailable());
        mobileMenu.setTenantCustom(originalMobileMenu.getTenantCustom());
        mobileMenu.setTenantAdminMenuId(originalMobileMenu.getTenantAdminMenuId());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<MobileMenu> uw = this.createUpdateQueryForNullValue(mobileMenu, mobileMenu.getMenuId());
        return mobileMenuMapper.update(mobileMenu, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long entryId) {
        LambdaQueryWrapper<MobileMenuDataPerm> qw = new LambdaQueryWrapper<>();
        qw.eq(MobileMenuDataPerm::getMenuId, entryId);
        if (mobileMenuDataPermMapper.selectCount(qw) > 0) {
            throw new MyRuntimeException("数据验证失败，当前数据正在被数据权限关联，不能删除！");
        }
        mobileMenuDataPermMapper.delete(qw);
        mobileMenuRoleMapper.delete(new LambdaQueryWrapper<MobileMenuRole>().eq(MobileMenuRole::getMenuId, entryId));
        return mobileMenuMapper.deleteById(entryId) == 1;
    }

    @Override
    public List<MobileMenu> getMobileMenuList(MobileMenu filter, String orderBy) {
        if (filter == null) {
            filter = new MobileMenu();
        }
        filter.setTenantId(TokenData.takeFromRequest().getTenantId());
        return mobileMenuMapper.getMobileMenuList(filter, orderBy);
    }

    @Override
    public List<MobileMenu> getMobileMenuListWithRelation(MobileMenu filter, String orderBy) {
        List<MobileMenu> resultList = this.getMobileMenuList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public List<MobileMenu> getMobileMenuListByRoleIds(String roleIds) {
        List<MobileMenu> commonEntryList =
                mobileMenuMapper.getCommonMobileMenuList(TokenData.takeFromRequest().getTenantId());
        if (StrUtil.isEmpty(roleIds)) {
            return commonEntryList.stream()
                    .sorted(Comparator.comparing(MobileMenu::getShowOrder, Comparator.naturalOrder()))
                    .collect(Collectors.toList());
        }
        Set<Long> roleIdSet = StrUtil.split(roleIds, StrUtil.COMMA).stream().map(Long::valueOf).collect(Collectors.toSet());
        List<MobileMenu> entryList =
                mobileMenuMapper.getMobileMenuListByRoleIds(roleIdSet, TokenData.takeFromRequest().getTenantId());
        CollUtil.addAll(entryList, commonEntryList);
        entryList = entryList.stream()
                .sorted(Comparator.comparing(MobileMenu::getShowOrder, Comparator.naturalOrder()))
                .collect(Collectors.toList());
        LinkedHashMap<Long, MobileMenu> entryMap = new LinkedHashMap<>();
        for (MobileMenu entry : entryList) {
            entryMap.put(entry.getMenuId(), entry);
        }
        return new LinkedList<>(entryMap.values());
    }

    private MobileMenu buildDefaultValue(MobileMenu mobileEntry) {
        if (mobileEntry.getMenuId() == null) {
            mobileEntry.setMenuId(idGenerator.nextLongId());
        }
        if (mobileEntry.getTenantAvailable() == null) {
            mobileEntry.setTenantAvailable(true);
        }

        if (mobileEntry.getTenantCustom() == null) {
            mobileEntry.setTenantCustom(true);
        }
        TokenData tokenData = TokenData.takeFromRequest();
        mobileEntry.setTenantId(tokenData.getTenantId());
        mobileEntry.setCreateUserId(tokenData.getUserId());
        mobileEntry.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        mobileEntry.setCreateTime(now);
        mobileEntry.setUpdateTime(now);
        MyModelUtil.setDefaultValue(mobileEntry, "imageData", "");
        return mobileEntry;
    }

    private void insertRelatedData(Long entryId, String roleIdListString) {
        if (StrUtil.isNotBlank(roleIdListString)) {
            Set<Long> roleIdSet =
                    StrUtil.split(roleIdListString, StrUtil.COMMA).stream().map(Long::valueOf).collect(Collectors.toSet());
            roleIdSet.forEach(roleId -> {
                MobileMenuRole o = new MobileMenuRole();
                o.setMenuId(entryId);
                o.setRoleId(roleId);
                mobileMenuRoleMapper.insert(o);
            });
        }
    }
}
